package cn.com.cetccst.sdk.utils;

import android.content.Context;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;

import java.io.File;
import java.lang.ref.SoftReference;


public class SSAPIUtil {

    private static SoftReference<Context> context;

    public static void init(Context cxt) {
        context = new SoftReference<>(cxt);
    }

    public static boolean isInitialised() {
        return context != null;
    }

    public static long getFileSize(Uri filePath) {
        if (context.get() != null) {
            try {
                ParcelFileDescriptor fileDescriptor = context.get().getContentResolver().openFileDescriptor(filePath, "r");
                if (fileDescriptor != null) {
                    return fileDescriptor.getStatSize();
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
        return 0;
    }

    public static String buildTransaction(final int type) {
        return (type < 0) ? String.valueOf(System.currentTimeMillis()) : (context.get().getPackageName() + "_" + type + "_" + System.currentTimeMillis());
    }

    public static String getFileExtensionFromUrl(String url) {
        if (!TextUtils.isEmpty(url)) {
            int fragment = url.lastIndexOf("#");
            if (fragment > 0) {
                url = url.substring(0, fragment);
            }

            int query = url.lastIndexOf("?");
            if (query > 0) {
                url = url.substring(0, query);
            }

            int filenamePos = url.lastIndexOf(File.separator);
            String filename = 0 <= filenamePos ? url.substring(filenamePos + 1) : url;
            // if the filename contains special characters, we don't
            // consider it valid for our matching purposes:
            if (!TextUtils.isEmpty(filename)) {
                int dotPos = filename.lastIndexOf(".");
                if (0 <= dotPos) {
                    return filename.substring(dotPos + 1);
                }
            }
        }
        return "";
    }
}
